'use strict';

const { PythonShell } = require('python-shell');
// const async = require('async');

// 获取Service类
const Service = require('egg').Service;

class DCMHService extends Service {
  async generanteImageCode(url) {
    const { ctx } = this;
    const python_options = {
      mode: 'text',
      pythonPath: '/Users/sam/miniforge3/envs/pytorch_env/bin/python3',
      scriptPath: '/Users/sam/Project/DCMH-PYTORCH/DCMH/',
      args: [ '--image_path', url ],
    };

    const result = await this.run('get_image_hash.py', python_options);
    const imageCode = ctx.helper.getHashCode(result.slice(url.length + 1));
    return imageCode;
  }

  async generanteTextCode(text) {
    const { ctx } = this;
    const python_options = {
      mode: 'text',
      pythonPath: '/Users/sam/miniforge3/envs/pytorch_env/bin/python3',
      scriptPath: '/Users/sam/Project/DCMH-PYTORCH/DCMH/',
      args: [ '--word', text ],
    };
    const result = await this.run('get_text_hash.py', python_options);
    const textCode = ctx.helper.getHashCode(result);
    return textCode;
  }

  async run(filePath, pythonOptions) {
    const result = await new Promise((resolve, reject) => {
      PythonShell.run(filePath, pythonOptions, (err, data) => {
        if (err) {
          reject(err);
        } else {
          resolve(data.toString('utf8'));
        }
      });
    });

    return result;
  }

  getSimilarity(origin, target) {
    const originArr = origin.split('');
    console.log(originArr);
    const targetArr = target.split('');
    console.log(targetArr);
    const num = targetArr.reduce((sum, item, index) => {
      const current = originArr[index];
      if (item === current) {
        return sum + 1;
      }
      return sum;

    }, 0);

    return num;
  }
}

module.exports = DCMHService;
